#!/usr/bin/env bash

set -eu

cd "$(dirname "$0")/.."

function clone_repo {
	owner=$1
	name=$2
	sha=$3

	path=examples/$name
	if [ ! -d "$path" ]; then
		echo "Cloning $owner/$name"
		git clone "https://github.com/$owner/$name" "$path"
	fi

	pushd "$path" >/dev/null
	actual_sha=$(git rev-parse HEAD)
	if [ "$actual_sha" != "$sha" ]; then
		echo "Updating $owner/$name to $sha"
		git fetch
		git reset --hard "$sha"
	fi
	popd >/dev/null
}

clone_repo golang go d75cc4b9c6e2acb4d0ed3d90c9a8b38094af281b
clone_repo moby moby ecbd126d6ac8c6818786f67e87f723543a037adb

known_failures="$(cat script/known-failures.txt)"

# shellcheck disable=2046
tree-sitter parse -q \
	'examples/**/*.go' \
	'!**/testdata/**/*' \
	'!**/go/test/**/*' \
	$(for failure in $known_failures; do echo "!${failure}"; done)

example_count=$(find examples -name '*.go' | grep -E -v -c 'go/test|testdata')
failure_count=$(wc -w <<<"$known_failures")
success_count=$((example_count - failure_count))
success_percent=$(bc -l <<<"100*${success_count}/${example_count}")

printf \
	"Successfully parsed %d of %d example files (%.1f%%)\n" \
	$success_count "$example_count" "$success_percent"
